package com.monkey.algorithm.chapter1

import java.util.*

/**
 * 作者：Monkey
 * 日期：2017/7/30
 */
fun main(args: Array<String>) {
    evaluate("( 1 + ( ( 2 * 3 ) * ( 4 * 5 ) ) )")
}

fun evaluate(expression: String) {
    val ops = Stack<String>()
    val vals = Stack<Double>()

    loop@ for (char in expression.split(" ")) {
        when (char) {
            "(" ->
                continue@loop
            "+", "-", "*", "/", "sqrt" ->
                ops.push(char)
            ")" -> {
                val op = ops.pop()
                val value = vals.pop()
                var temp: Double? = null
                when (op) {
                    "+" -> {
                        temp = vals.pop() + value
                    }
                    "-" -> {
                        temp = vals.pop() - value
                    }
                    "*" -> {
                        temp = vals.pop() * value
                    }
                    "/" -> {
                        temp = vals.pop() / value
                    }
                }
                vals.push(temp)
            }
            else ->
                vals.push(char.toDouble())
        }
    }
    println(vals[0])
}